package com.jiezuo.flowable.listener;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.flowable.common.engine.api.delegate.event.FlowableEvent;
import org.flowable.common.engine.api.delegate.event.FlowableEventListener;
import org.flowable.common.engine.impl.cfg.TransactionState;
import org.flowable.engine.RepositoryService;
import org.flowable.engine.delegate.event.impl.FlowableEntityEventImpl;
import org.flowable.engine.repository.ProcessDefinition;
import org.flowable.engine.runtime.ProcessInstance;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

/**
 *@Description 添加流程实例结束全局监听 （工作流结束，告知发起人）
 *@Author 庞留杰
 *@Date2021/5/10 10:03
 *@Version V1.0
 **/
@Slf4j
@Component
@RequiredArgsConstructor
public class GlobalProcessCompletedListener implements FlowableEventListener {

    private final RepositoryService repositoryService;

    @Override
    public void onEvent(FlowableEvent flowableEvent) {
            log.info(">>>>>>>>>>>>>>>>>> 进入工作流 ProcessCompleted 全局监听器 >>>>>>>>>>>>>>>>>>");
            // BussClient bussClient = SpringUtil.getObject(BussClient.class);
            ProcessInstance processInstance = (ProcessInstance) ((FlowableEntityEventImpl) flowableEvent).getEntity();
            String startUserId = processInstance.getStartUserId();//发起人
            String processInstanceId = processInstance.getProcessInstanceId();
            System.out.println("processInstanceId = " + processInstanceId);
            Map<String,String> params = new HashMap<>();
            params.put("processInstanceId", processInstanceId);
            params.put("activityId", "");
            params.put("activityName", "已完结");
            // Result result = bussClient.processCompleted(params);//即使失败也不会回滚事务...
            String processDefinitionId = processInstance.getProcessDefinitionId();
            ProcessDefinition processDefinition = repositoryService.createProcessDefinitionQuery().processDefinitionId(processDefinitionId).singleResult();

//            FinanceClient financeClient = SpringUtil.getObject(FinanceClient.class);
//            Result result = financeClient.processCompleted(params);
//            if (!result.isSuccess()) {
//                throw new BusinessRuntimeException(result.getMessage());//调用失败，抛出异常
//            }

    }

    @Override
    public boolean isFailOnException() {
        return true;
    }

    @Override
    public boolean isFireOnTransactionLifecycleEvent() {
        return true;
    }

    @Override
    public String getOnTransaction() {
        //事务提交后触发
        return TransactionState.COMMITTED.name();
    }
}
